﻿#region license

/* 
    -------------------------------------------------------------------------------
                     Copyright 2013 Gabriele Gindro 
    -------------------------------------------------------------------------------
  
  	Versione libreria: 1.0 
  	
  	-------------------------------------------------------------------------------
  	
  	Dipendenze:
  	
 	- Microsoft .NET Framework versione 4.0 o successiva
 	
 	- Sistemi x86 e x64
	
  	Questo programma è stato creato con SharpDevelop 4.3.1.9430-406354be
  	
    -------------------------------------------------------------------------------
    
 */

#endregion

#region using

using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.ComponentModel;

#endregion

namespace maillib
{
	
	public delegate void EventSended(object sender, SendedEventArgs e);
	
	#region mail class
	
	/// <summary>
	/// Libreria mail per l'invio di email
	/// </summary>
	public class mail
	{
		#region varibles
		
		public event EventSended OnSended;
		
		public BackgroundWorker worker;
		
		public string email { get; private set; }
		public string password { get; private set; }
		public string smtp { get; private set; }
		public int port { get; private set; }
		public bool enableSsl { get; private set; }
		public SmtpDeliveryMethod smtp_delivery_method { get; private set; }	
		
		#endregion
		
		#region methods
		
		/// <summary>
		/// Costruttore
		/// </summary>
		/// <param name="email">Email</param>
		/// <param name="password">Password dell'email</param>
		/// <param name="smpt">Indirizzo smtp</param>
		/// <param name="port">Porta inidirizzo smtp</param>
		/// <param name="enableSsl">Indica se bisogna utilizzare una connessione crittografata, di default è true (Opzionale)</param>
		/// <param name="smpt_delivery_method">Indica il tipo di metodo di spedizione posta, di default è Network (Opzionale)</param>
		public mail(string email, string password, string smtp, int port, bool enableSsl = true, SmtpDeliveryMethod smpt_delivery_method = SmtpDeliveryMethod.Network)
		{
			this.email = email;
			this.password = password;
			this.smtp = smtp;
			this.port = port;
			this.enableSsl = enableSsl;
			this.smtp_delivery_method = smtp_delivery_method;
		}
		
		/// <summary>
		/// Invia un messaggio di posta elettronica
		/// </summary>
		/// <param name="address">Lista di destinatari</param>
		/// <param name="subject">Oggetto del messaggio</param>
		/// <param name="body">Corpo del messaggio</param>
		/// <param name="isHtml">Indica se la formattazione per il corpo del messaggio deve essere html, di default è false (Opzionale)</param>
		public void Send(List<string> address, string subject, string body, bool isHtml = false)
		{
			if (worker == null)
			{
				worker = new BackgroundWorker();
				worker.WorkerReportsProgress = false;
				worker.WorkerSupportsCancellation = true;
				worker.DoWork += new DoWorkEventHandler(DoWork);
				worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
				object[] param = new object[] { address, subject, body, isHtml };
				worker.RunWorkerAsync(param);
			}
		}

		/// <summary>
		/// Avvia il processo asincrono di invio del messaggio
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void DoWork(object sender, DoWorkEventArgs e)
		{
			if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
				throw new Exception("network not available");
			object[] args = e.Argument as object[];
			using (MailMessage message = new MailMessage())
			{
				for (int i = 0; i < ((List<string>)args[0]).Count; i++)
					message.To.Add(new MailAddress(((List<string>)args[0])[i]));
				message.From = new MailAddress(email);
				message.Subject = (string)args[1];
				message.Body = (string)args[2];
				message.IsBodyHtml = (bool)args[3];
				using (SmtpClient smtpclient = new SmtpClient(smtp, port))
				{
					smtpclient.EnableSsl = enableSsl;
					smtpclient.DeliveryMethod = smtp_delivery_method;
					smtpclient.UseDefaultCredentials = false;
					smtpclient.Credentials = new System.Net.NetworkCredential(email, password);
					smtpclient.Send(message);
				}
			}
		}
		
		/// <summary>
		/// Evento che si scatena quando il processo di invio è stato completato
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
		{
			SendedEventArgs sea = new SendedEventArgs();
			if (e.Error != null)
			{
				sea.error = e.Error.Message;
				Sended(sea);
			}
			else
				Sended(sea);
			Dispose();
		}
		
		/// <summary>
		/// Rilascia tutte le risorse associate agli eventi
		/// </summary>
		private void Dispose()
		{
			if (OnSended != null)
				OnSended = null;
			worker = null;
		}
		
		#endregion
		
		#region events
		
		/// <summary>
		/// Evento interno
		/// </summary>
		/// <param name="e"></param>
		protected virtual void Sended(SendedEventArgs e)
		{
			var h = OnSended;
			if (h != null)
				h(this, e);
		}
		
		#endregion
	}
	
	#endregion
	
	#region class events
	
	/// <summary>
	/// Classe per i parametri dell'evento associato
	/// </summary>
	public class SendedEventArgs : EventArgs
	{
		public string error = null;
	}
	
	#endregion
}